/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.una.pol.ii.is2.reporter;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 *
 * @author markos
 */
public class SAVReporter {
    private Connection conn;
    private Context context;

    private void getConnection()throws SQLException, NamingException{
        context = new InitialContext();
        DataSource ds = (DataSource) context.lookup("jdbc/sav");
        conn = ds.getConnection();
        if(conn != null){
            System.out.println("No soy null markos.");
        }
    }

    private void closeConnection()throws SQLException{
        conn.close();
    }
    
    public void getReport(String sNameReport, Map parameters, ServletContext sc, String format)
            throws Exception {
        String realPathXml = sc.getRealPath("reportes/");
        getConnection();
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(realPathXml + "/" + sNameReport);
            System.out.println("path : " + realPathXml + "/" + sNameReport);

            byte[] pdf = null;

            pdf = JasperRunManager.runReportToPdf(jasperReport, parameters, conn);
            FacesContext faces = FacesContext.getCurrentInstance();
            HttpServletResponse response =
                    (HttpServletResponse) faces.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setContentLength(pdf.length);
            response.setHeader("Content-disposition", "inline; filename=\"MyPdf.pdf\"");

            ServletOutputStream out = response.getOutputStream();
            out.write(pdf);

            faces.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally{
            closeConnection();
        }
    }
}
